package com.hspedu.newData.dmsxl.树.二叉树的遍历.层序遍历迭代法.队列;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-23 
 * @Version: 1.0
 */

public class LC117填充每个节点的下一个右侧节点指针Ⅱ {

    public Node connect(Node root) {
        if (root == null) return null;
        Queue<Node> queue = new LinkedList<>();

        queue.offer(root);

        while(!queue.isEmpty()){

            int len = queue.size();
            while(len > 0){
                Node node = queue.poll();
                if (len != 1){
                    node.next = queue.peek();
                }

                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);

                len --;
            }
        }
        return root;
    }
}
